package controllers

import (
	"XYZShell/mgotool/models"
	"strconv"

	"github.com/astaxie/beego"
	"github.com/zxfonline/json"
	"gopkg.in/mgo.v2/bson"
)

type JsonApiController struct {
	beego.Controller
}

//select
func (this *JsonApiController) Get() {
	dbname := this.Ctx.Input.Param(":dbname")
	c := this.Ctx.Input.Param(":c")
	var mgotool *models.Mgotool
	mgotool = models.GetMgotool()
	var jsonstr interface{}
	if c == "__status__" {
		jsonstr = mgotool.GetDbStats(dbname)
	} else if c == "__server_status__" {
		jsonstr = mgotool.GetServerStatus()
	} else {
		page := this.Ctx.Input.Query("p")
		pagesize := this.Ctx.Input.Query("psize")
		p, _ := strconv.Atoi(page)
		psize, _ := strconv.Atoi(pagesize)
		bs := bson.M{}
		json.Unmarshal([]byte(mgotool.GetJsonData(dbname, c, p, psize)), &bs)
		jsonstr = bs
	}

	this.Data["json"] = jsonstr
	this.ServeJSON()
}

//select,update
func (this *JsonApiController) Post() {
	dbname := this.Ctx.Input.Param(":dbname")
	c := this.Ctx.Input.Param(":c")
	var mgotool *models.Mgotool
	mgotool = models.GetMgotool()
	t := this.Ctx.Input.Query("type")
	rs := ""
	if t == "d" {
		id := this.Ctx.Input.Query("id")
		rs = mgotool.DeleteCollection(dbname, c, id)
	} else if t == "u" {
		jsstr := this.Ctx.Input.Query("json")
		rs = mgotool.UpdateCollection(dbname, c, jsstr)
	}

	this.Data["json"] = rs
	this.ServeJSON()
}

//ass
func (this *JsonApiController) Put() {

}

//del
func (this *JsonApiController) Delete() {

}
